#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from upload.models import Upload
from django.http import HttpResponse, Http404
from documents.models import Document, Item, ModuleTerm, ModulePart
from shared.helper import render_to_response
from django.core.urlresolvers import reverse
from upload.forms import UploadForm
from django.shortcuts import redirect
import settings
from django.forms.forms import Form
from documents.forms import ItemForm, DocumentForm
from documents.itemtype import ItemType
import os

@login_required
def upload(request, item_id):
    """
    The upload view shows information for an Upload
    """
    
    upload = Upload.objects.get(item__id=item_id)
    
    item = upload.item
    
    item.views = item.views + 1
    item.save()
    
    if(item.activated == False):
        raise Http404
    
    abs_filename = os.path.join(settings.DOWNLOAD_ROOT, upload.upload.name)
    response = HttpResponse() # 200 OK
    del response['content-type'] # We'll let the web server guess this.
    response['X-Sendfile'] = abs_filename
    response['Content-Disposition'] = 'attachment;filename=' + upload.upload.name
    return response

@login_required
def add_document_upload(request, module_part_id, module_term_id):
    """
    The add_document_upload is a mixture of add_document and add_upload
    It is treated like "Hey I've got an Upload ready and there is no
    Document for this yet." But it also handles the case that there
    already exists a Document like this.
    """
    
    module_part = ModulePart.objects.get(id = module_part_id)
    module_term = ModuleTerm.objects.get(id = module_term_id)
    
    document = Document (
                         module_part = module_part,
                         module_term = module_term,
                         user = request.user
                        )
    
    if request.method == 'POST':
        document_form = DocumentForm(request.POST, instance = document)
        item_form = ItemForm(request.POST)
        upload_form = UploadForm(request.POST, request.FILES)
        if document_form.is_valid() and item_form.is_valid() and upload_form.is_valid():
            document = document_form.save()
            
            item = item_form.save(commit = False)
            item.document = document
            item.user = request.user
            item.item_type = ItemType.get_item_type_for_model(Upload)
            item.save()
            
            upload_form.instance.item = item
            upload_form.save()
            
            return redirect(reverse('documents.views.module', kwargs={ 'module_term_id': module_term.id }))
    else:
        document_form = DocumentForm()
        item_form = ItemForm()
        upload_form = UploadForm()
    
    return render_to_response(
                                request,
                                'upload/add_document_upload.html',
                                {
                                    'document_form': document_form,
                                    'item_form': item_form,
                                    'upload_form': upload_form,
                                    'module_part': module_part,
                                    'module_term': module_term
                                }
                             )

@login_required
def add_upload(request, document_id):
    """
    The add_upload view allows us to add an Upload
    """

    # Get Upload context
    document = Document.objects.get(id = document_id)
    
    # Create the needed base for the Item
    item = Item(
                    document = document,
                    user = request.user,
                    item_type = ItemType.get_item_type_for_model(Upload)
               )
    
    # If the form has already been filled in
    if request.method == 'POST':
        item_form = ItemForm(request.POST, instance = item)
        upload_form = UploadForm(request.POST, request.FILES)
        if item_form.is_valid() and upload_form.is_valid(): # All validation rules pass
            item = item_form.save()
            
            upload_form.instance.item = item
            
            upload_form.save()
            
            return redirect(reverse('documents.views.module', kwargs={ 'module_term_id': document.module_term.id }))
    
    # If the form has yet to be filled in
    else:
        item_form = ItemForm()
        upload_form = UploadForm()
        
    return render_to_response(
                                request,
                                'upload/add_upload.html',
                                {
                                    'item_form': item_form,
                                    'upload_form': upload_form,
                                    'document': document,
                                }
                             )


@login_required
def delete_upload(request, item_id):
    """
    View for deleting an upload - allowed when you have delte right for uploads or are owner
    """
    
    upload = Upload.objects.get(item__id = item_id)
    
    if not (request.user.has_perm('documents.delete_item') or request.user == upload.item.user):
        return redirect(settings.LOGIN_URL)
    
    if request.method == 'POST':
        document = upload.item.document
        upload.item.delete()
        return redirect(reverse('documents.views.module', kwargs={ 'module_term_id': document.module_term.id }))
    
    form = Form()
    return render_to_response(
                                request,
                                'upload/delete_upload.html',
                                {
                                    'form': form,
                                    'upload': upload
                                }
                             )
    

@login_required
def change_upload(request, item_id):
    """
    The change_upload view allows us to change an Upload - possible if you have the right, or are the owner
    """

    upload = Upload.objects.get(item__id = item_id)
    
    if not (request.user.has_perm('upload.change_upload') or request.user == upload.item.user):
        return redirect(settings.LOGIN_URL)
    
    # If the form has already been filled in
    if request.method == 'POST':
        item_form = ItemForm(request.POST, instance = upload.item)
        upload_form = UploadForm(request.POST, request.FILES, instance = upload)
        if item_form.is_valid() and upload_form.is_valid(): # All validation rules pass
            item_form.save()
            upload_form.save();
            
            return redirect(reverse('documents.views.module', kwargs={ 'module_term_id': upload.item.document.module_term.id }))
    
    # If the form has yet to be filled in
    else:
        item_form = ItemForm(instance = upload.item)
        upload_form = UploadForm(instance = upload)
        
    return render_to_response(
                                request,
                                'upload/change_upload.html',
                                {
                                    'item_form': item_form,
                                    'upload_form': upload_form,
                                    'upload': upload,
                                }
                             )